import jwtDecode from 'jwt-decode'
import VueCookie from 'vue-cookie'

export default {
  getActiveUser: function () {
    let uid = this.getCookie('uid')
    if (uid) {
      let activeUserStr = this.getUserSession('activeUser')
      return JSON.parse(activeUserStr)
    } else {
      this.delUserSession('activeUser')
    }
  },
  getCookie: function (name) {
    return VueCookie.get(name)
  },
  // 获取jwt令牌
  getJwt: function () {
    let activeUser = this.getActiveUser()
    if (activeUser) {
      return activeUser.jwt
    }
  },
  // 解析jwt令牌，获取用户信息
  getUserInfoFromJwt: function (jwt) {
    if (!jwt) {
      return
    }
    var jwtDecodeVal = jwtDecode(jwt)
    if (!jwtDecodeVal) {
      return
    }
    let activeUser = {}
    // console.log(jwtDecodeVal)
    activeUser.username = jwtDecodeVal.username || ''
    activeUser.userid = jwtDecodeVal.id || ''
    activeUser.authorities = jwtDecodeVal.authorities || ''
    activeUser.name = jwtDecodeVal.name || ''
    activeUser.uid = jwtDecodeVal.jti || ''
    activeUser.jwt = jwt
    return activeUser
  },
  getUserSession: function (key) {
    return sessionStorage.getItem(key)
  },
  setUserSession: function (key, value) {
    return sessionStorage.setItem(key, value)
  },
  delUserSession: function (key) {
    return sessionStorage.removeItem(key)
  },
  getQueryStringByName: function (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    var context = ''
    if (r != null) {
      context = r[2]
    }
    reg = null
    r = null
    return context || ''
  }

}
